<template>
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    width="1700px"
    draggable
    @close="closeDialog"
  >
    <el-form
      ref="formRef"
      :model="tableData"
      :inline="true"
      :rules="rules"
      label-width="160"
    >
      <el-row>
        <el-col :span="17">
          <el-form :model="searchParam" :inline="true">
            <el-form-item label="成品物料">
              <el-input
                v-model="searchParam.materialCode"
                placeholder="请选择成品物料"
                clearable
                readonly
                @click="showWorkOrderSelect"
              >
                <template #append>
                  <el-button type="success" plain @click="showWorkOrderSelect"
                    >选择</el-button
                  >
                </template>
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="search"
                ><i-ep-search />搜索</el-button
              >
              <el-button @click="reset"><i-ep-refresh />重置</el-button>
            </el-form-item>
          </el-form>
          <el-card shadow="never" class="table-container">
            <el-table
              ref="bomSelectTableRef"
              v-loading="tableLoading"
              :data="tableData"
              highlight-current-row
              @selection-change="handleSelectionChange"
              row-key="id"
              border
              style="height: 400px"
              :tree-props="{ children: 'nodes', hasChildren: 'hasChildren' }"
            >
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column
                label="物料编码"
                prop="materialCode"
                min-width="100"
                show-overflow-tooltip
                align="left"
              />
              <el-table-column
                label="物料名称"
                prop="materialName"
                min-width="100"
                show-overflow-tooltip
                align="center"
              />
              <el-table-column
                label="物料短号"
                prop="figureNumber"
                min-width="100"
                show-overflow-tooltip
                align="center"
              />
              <el-table-column
                label="物料类型"
                prop="materialType"
                min-width="100"
                show-overflow-tooltip
                align="center"
              />
            </el-table>
            <el-pagination
              :background="true"
              :current-page="pageable.pageNum"
              :page-size="pageable.pageSize"
              :page-sizes="[10, 25, 50, 100]"
              :total="pageable.total"
              layout="total, sizes, prev, pager, next, jumper"
              class="mt-[20px]"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
            <div style="float: right">
              <el-button
                type="primary"
                :disabled="ids.length === 0"
                style="margin-bottom: 10px"
                @click="selected"
                >选中 >></el-button
              >
            </div>
          </el-card>
        </el-col>

        <el-col :span="1" />
        <el-col :span="6">
          <div>
            <el-form :inline="true">
              <el-form-item label=" " style="" />
            </el-form>
          </div>
          <el-card shadow="never" class="table-container">
            <el-table
              :data="indexFormData.data"
              :key="Math.random"
              border
              style="height: 400px"
            >
              <el-table-column
                label="物料编码"
                prop="materialCode"
                min-width="70"
              />
              <el-table-column
                label="物料名称"
                prop="materialName"
                min-width="70"
              />
              <el-table-column label="删除" min-width="25">
                <template #header>
                  <el-button type="danger" size="small" link @click="removeAll"
                    ><i-ep-delete />
                  </el-button>
                </template>
                <template #default="scope">
                  <el-button
                    type="danger"
                    size="small"
                    link
                    @click="removeItem(scope.row)"
                    ><i-ep-delete
                  /></el-button>
                </template>
              </el-table-column> </el-table
          ></el-card>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" :loading="loading" @click="handleSubmit"
          >保 存</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>

    <mesbatchnumberrule-material
      :visible="selectDialogSELECT.visible"
      @change-visible="changeVisibleSELECT"
      :plantId="searchParam.plantId"
      :brekList="brekList"
    />
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useTable } from "@/utils/useTable";
import { ElForm } from "element-plus";

defineOptions({
  name: "MESBATCHNUMBERRULEBOMTREE",
  inheritAttrs: false,
});

const treeKey = ref(Math.random());

// 请求参数
const requestApi = "/mes/mdmmaterial/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  bomCode: "",
  plantId: "",
  materialCode: "",
  filterLeaf: true,
};

const deleteParam = {
  api: "/mes/mesbom/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

const selectedRows = ref([]);
const ids = ref([]);
const bomSelectTableRef = ref(null);

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行
const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  ruleId: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

let indexFormData = reactive({
  data: [],
});

watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

watch(
  () => props.data,
  (newVal: any) => {
    const data = newVal;
    Object.assign(indexFormData.data, data);
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
  Object.assign(searchParam, searchParamInit);
}
// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  loading: tableLoading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

//选择物料弹窗
const selectDialogSELECT = ref({
  visible: false,
});
const changeVisibleSELECT = (val: boolean, data: any) => {
  selectDialogSELECT.value.visible = val;
  if (data) {
    searchParam.value.materialId = data.id;
    searchParam.value.materialCode = data.materialCode;
    getTableList();
  }
};
// 回显的数据
const brekList = ref([]);
const showWorkOrderSelect = () => {
  selectDialogSELECT.value.visible = true;
};

const handleSelectionChange = (val) => {
  if (val.length === 0) {
    selectedRows.value = [];
    ids.value = [];
    return;
  }
  console.log("val:", val);
  const filteredRows = val;
  selectedRows.value = filteredRows;
  ids.value = filteredRows.map((row) => row.id);
};

const selected = () => {
  const rowsList = selectedRows.value.filter((item: any) => {
    const rowList = indexFormData.data.filter((item2: any) => {
      return item.id == item2.id;
    });
    return rowList.length == 0;
  });
  indexFormData.data = indexFormData.data.concat(rowsList);
};

/** 弹窗显示 **/
const visibleDialog = ref(false);

/** formData定义表单数据 */
const formRef = ref(ElForm);
/** rules规则 */
const rules = reactive({
  bomId: [{ required: true, message: "请选择BOM", trigger: "blur" }],
});

/** 重置表单 */
function resetForm() {
  if (bomSelectTableRef.value != null) {
    bomSelectTableRef.value.clearSelection();
  }
  formRef.value.resetFields();
  formRef.value.clearValidate();
  treeKey.value = Math.random();
  indexFormData.data = [];
}

const loading = ref(false);

async function handleSubmit() {
  const materialId = indexFormData.data.map((item) => item.id);
  loading.value = true;
  await request({
    url: "/mes/mesbatchnumberrulematerial/updateByRuleId",
    method: "post",
    data: { ruleId: props.ruleId, materialId: materialId },
  }).finally(() => {
    loading.value = false;
  });
  ElMessage.success(`成功`);
  closeDialog();
}

const removeAll = () => {
  selectedRows.value = [];
  ids.value = [];
  indexFormData.data = [];
};

const removeItem = (row) => {
  console.log("row", row);
  indexFormData.data = indexFormData.data.filter(
    (item: any) => item.id !== row.id
  );
};

onMounted(() => {
  getTableList();
});
</script>
